<?php

function encode_ip($dotquad_ip) {
    $ip_sep = explode('.', $dotquad_ip);
    return sprintf('%02x%02x%02x%02x', $ip_sep[0], $ip_sep[1], $ip_sep[2], $ip_sep[3]);
}

function bb2html($output)
{
    $output = str_replace("[b]","<b>",$output);
    $output = str_replace("[B]","<b>",$output);
    $output = str_replace("[i]","<i>",$output);
    $output = str_replace("[I]","<i>",$output);
    $output = str_replace("[/b]","</b>",$output);
    $output = str_replace("[/B]","</b>",$output);
    $output = str_replace("[/i]","</i>",$output);
    $output = str_replace("[/I]","</i>",$output);

    $bbreplace = '/\[url\=(.*?)\](.*?)\[\/url\]/is';
    $bbreplacements = '<a href="$1" target="_blank">$2</a>';
    $output = preg_replace($bbreplace, $bbreplacements, $output);

    return $output;
}

function formatOutput($output) {
    $output = nl2br(stripslashes(urldecode($output)));
    return bb2html($output);
}

function formspecialchars($var)
    {
        if (is_array($var)) {
            $out = array();
            foreach ($var as $key => $v) {
                $out[$key] = formspecialchars($v);
            }
        } else {
            $out = htmlspecialchars_decode($var);
            $out = htmlspecialchars(stripslashes(trim($out)), ENT_QUOTES);
        }

        return $out;
    }

function mynl2br($text) {
   return strtr($text, array("\\r\\n" => '<br />', "\\r" => '<br />', "\\n" => '<br />'));
}
function no_magic_quotes($query) {
        $data = explode("\\",$query);
        $cleaned = implode("",$data);
        return $cleaned;
}
function formatEmail($output){
    return bb2html(no_magic_quotes(mynl2br($output)));
}


function formatFormOutput($output) {
    $output = stripslashes(urldecode($output));
    return $output;
}


function formatArrayOutput($output, $form=false) {
    foreach($output as $key=>$value) {
        if($form)
            $output[$key] = formatFormOutput($value);
        else
            $output[$key] = formatOutput($value);

    }

    return $output;
}


function formatJSOutput($output) {
    $output = htmlspecialchars($output);
    //$output = str_replace("<br />","<br>",$output);

    return $output;
}

function formatTimestamp($timestamp, $format) {
    if($timestamp > 0) {

        $ms = $timestamp % 1000;
        if($ms > 99) {
            $ms = '.' . $ms;
        }
        else if($ms > 9) {
                $ms = '.0' . $ms;
            }
            else {
                $ms = '.00' . $ms;
            }
        $ms = sprintf("%-04s",   $ms);
		/*$s = $timestamp % (1000 * 60);
		$s = sprintf("%-02s",   $s);
		$m = $timestamp % (1000 * 60 * 60);
		$m = sprintf("%-02s",   $m);
		$h = $timestamp / (1000 * 60 * 60);

		return $h . ':' . $m . ':' . $s . '.'. $ms;*/
        $timestamp = ($timestamp / 1000);// + (5*60*60);
        return gmstrftime($format, $timestamp) . $ms;
    }
    else {
        return '';
    }
}

function check_email_address($email) {
  // First, we check that there's one @ symbol,
  // and that the lengths are right.
  if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
    // Email invalid because wrong number of characters
    // in one section or wrong number of @ symbols.
    return false;
  }
  // Split it into sections to make life easier
  $email_array = explode("@", $email);
  $local_array = explode(".", $email_array[0]);
  for ($i = 0; $i < sizeof($local_array); $i++) {
    if
(!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&
↪'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$",
$local_array[$i])) {
      return false;
    }
  }
  // Check if domain is IP. If not,
  // it should be valid domain name
  if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) {
    $domain_array = explode(".", $email_array[1]);
    if (sizeof($domain_array) < 2) {
        return false; // Not enough parts to domain
    }
    for ($i = 0; $i < sizeof($domain_array); $i++) {
      if
(!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|
↪([A-Za-z0-9]+))$",
$domain_array[$i])) {
        return false;
      }
    }
  }
  return true;
}

function decodeAvatar($avatar, $type) {
    global $properties, $www_forums;

    if($type == 2 && strtolower(substr($avatar,0,5)) == 'http:') {
        return $avatar;
    }
    else if($type == 1) {
            return $www_forums . 'download/file.php?avatar='. $avatar;
        }
        else if($type == 3) {
                if($avatar[0] == 'g')
                    $avatar = substr($avatar,1);

                return $www_forums . $properties['forum_avatar_dir'] . $avatar;
            }
            else if($type == 4) {
                    return $avatar;
                }
                else {
                    return '';
                }
}

function createString($length) {

    $chars = "abcdefghijkmnopqrstuvwxyz023456789";
    srand((double)microtime()*1000000);
    $i = 0;
    $pass = '' ;

    while ($i < $length) {
        $num = rand() % 33;
        $tmp = substr($chars, $num, 1);
        $pass = $pass . $tmp;
        $i++;
    }

    return substr($pass, 0, $length);

}

function filename_extension($filename) {
    $pos = strrpos($filename, '.');
    if($pos===false) {
        return false;
    } else {
        return substr($filename, $pos+1);
    }
}

function resizeToHeight($height, $imagea) {
    $ratio = $height / getHeight($imagea);
    $width = getWidth($imagea) * $ratio;
    return resize($width,$height, $imagea);
}

function resize($width,$height, $imagea) {
    $new_image = imagecreatetruecolor($width, $height);
    imagecopyresampled($new_image, $imagea, 0, 0, 0, 0, $width, $height, getWidth($imagea), getHeight($imagea));
    return $new_image;
} 

function getWidth($imagea) {
    return imagesx($imagea);
}
function getHeight($imagea) {
    return imagesy($imagea);
} 

function cropImage($nw, $nh, $source, $cropToHeight = true) {

// Get new dimensions
    $width_orig=getWidth($source);
    $height_orig=getHeight($source);

    $newsize_w = $nw ;
    $newsize_h = $nh ;
    $width = $nw ;
    $height = $nh ;

    if($cropToHeight) {
        if ($width_orig < $height_orig) {
            $height = ($newsize_w / $width_orig) * $height_orig;
        } else {
            $width = ($newsize_h / $height_orig) * $width_orig;
        }

        if ($width < $newsize_w)
        //if the width is smaller than supplied thumbnail size
        {
            $width = $newsize_w;
            $height = ($newsize_w/ $width_orig) * $height_orig;;
        }

        if ($height < $newsize_h)
        //if the height is smaller than supplied thumbnail size
        {
            $height = $newsize_h;
            $width = ($newsize_h / $height_orig) * $width_orig;
        }
    }
    else {
        if ($width_orig > $height_orig) {
            $height = ($newsize_w / $width_orig) * $height_orig;
        } else {
            $width = ($newsize_h / $height_orig) * $width_orig;
        }

        if ($width > $newsize_w)
        //if the width is smaller than supplied thumbnail size
        {
            $width = $newsize_w;
            $height = ($newsize_w/ $width_orig) * $height_orig;;
        }
        else {
            $newsize_w = $width;
        }

        if ($height > $newsize_h)
        //if the height is smaller than supplied thumbnail size
        {
            $height = $newsize_h;
            $width = ($newsize_h / $height_orig) * $width_orig;
        }
        else {
            $newsize_h = $height;
        }
    }

    $res_image = imagecreatetruecolor($width , $height);
    imagealphablending($res_image, true);

    $white_background = imagecolorallocate($res_image, 255, 255, 255);
    imagefill($res_image, 0, 0, $white_background);

    imagecopyresampled($res_image, $source, 0, 0, 0, 0,
        $width, $height, $width_orig, $height_orig);
    // true color for best quality
    // make the background color white //
    $res_image2 = imagecreatetruecolor($newsize_w , $newsize_h);
    $white_background = imagecolorallocate($res_image2, 255, 255, 255);

    // change the background to white //
    imagefill($res_image2, 0, 0, $white_background);
    $w1 =($width/2) - ($newsize_w/2);
    $h1 = ($height/2) - ($newsize_h/2);

    imagealphablending($res_image2, true);

    imagecopyresampled($res_image2, $res_image, 0,0, $w1, $h1,
        $newsize_w , $newsize_h ,$newsize_w, $newsize_h);

    return $res_image2;
}

//xml parsing functions


function startElementHandler ($parser,$name,$attrib) {
    global $state;
    //echo $name;
    $state=$name;
}


function characterDataHandler ($parser, $data) {
    global $drivercount;
    global $drivers;
    global $state;

    if (!$state) {
        return;
    }
    if ($state=="NAME") {
        $drivers[$drivercount]["Name"] = $data;
        $drivers[$drivercount]["Laps"] = Array();
    }
    if ($state=="LAP") {
        $drivers[$drivercount]["Laps"][] = $data;
    }
    if($state=="CARTYPE") {
        $drivers[$drivercount]["Car"] = $data;
    }
}

function endElementHandler ($parser,$name) {
    global $drivercount;
    global $state;
    //echo $name;
    $state='';
    if($name=="DRIVER") {$drivercount++;}
}

function getAdminControls($action, $itemID) {
    if(isset($_SESSION['valid_admin']) && $_SESSION['valid_admin'] > 1) {
        global $skin_dir, $lang;

        ob_start();
        include $skin_dir . 'tpl/adminLinks.tpl';
        $contents = ob_get_contents();
        ob_end_clean();

        return $contents;
    }
    else {
        return '';
    }
}

?>